package com.hzit.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * dispatcherTypes:过滤器的类型，默认是REQUEST
 */
@WebFilter(filterName = "loginFilter", urlPatterns = {"/*"}, dispatcherTypes = {DispatcherType.REQUEST, DispatcherType.FORWARD})
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化...");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        //当前请求被拦截之后，处理的业务逻辑

        HttpServletRequest request1 = (HttpServletRequest) request;
        HttpServletResponse response1 = (HttpServletResponse) response;

        //放行指定的请求  /jsp/Login.jsp    /user/login    /user/reg.jsp   /user/reg
        String servletPath = request1.getServletPath();
        if ("/jsp/Login.jsp".equals(servletPath) || "/user/login".equals(servletPath)) {
            chain.doFilter(request1, response1);
            System.out.println("成功被放行:" + servletPath);
            return;
        }


        System.out.println(request1.getRequestURL());
        HttpSession session = request1.getSession();
        Object userInfo = session.getAttribute("userInfo");
        //放行的依据：是否登录   登录成功之后:session -->userInfo  判断该属性是否为空

        //1.登录 直接放行
        if (userInfo != null) {
            //放行
            chain.doFilter(request1, response);

            System.out.println("Filter成功返回....");
        } else {
            //2.未登录 跳转到登录页面
            response1.sendRedirect(request1.getContextPath() + "/jsp/Login.jsp");
        }


    }

    @Override
    public void destroy() {
        System.out.println("销毁.....");
    }
}
